<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="65%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="渠道名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入渠道名称" @blur="checkExist" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="渠道区域" prop="location">
            <el-cascader
              v-model="formData.location"
              :options="areaList"
              :props="defaultProps"
              class="w-1/1"
              clearable
              filterable
              placeholder="渠道区域"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入详细地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactName">
            <el-input v-model="formData.contactName" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactNumber">
            <el-input v-model="formData.contactNumber" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关系评估" prop="relationLevel">
            <el-select v-model="formData.relationLevel" placeholder="请选择关系评估">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_EXPAND_CHANNEL_RELATION_LEVEL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="渠道评估" prop="channelLevel">
            <el-select v-model="formData.channelLevel" placeholder="请选择渠道评估">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_EXPAND_CHANNEL_LEVEL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="主推我司产品" prop="mainProduct">
            <el-input v-model="formData.mainProduct" placeholder="请输入主推我司产品" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="计量方式" prop="countMethod">
            <el-input v-model="formData.countMethod" placeholder="请输入计量方式" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收益说明" prop="revenueDescribe">
            <el-input v-model="formData.revenueDescribe" placeholder="请输入收益说明" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="转介情况" prop="transferIntroduceSituation">
            <el-select v-model="formData.transferIntroduceSituation" placeholder="请选择转介情况">
              <el-option
                v-for="dict in getStrDictOptions(
                  DICT_TYPE.BIZ_EXPAND_CHANNEL_TRANSFER_INTRODUCE_SITUATION
                )"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="政府资源" prop="govSource">
            <el-input v-model="formData.govSource" placeholder="请输入政府资源" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="企业/个人资源" prop="personalSource">
            <el-input v-model="formData.personalSource" placeholder="请输入企业/个人资源" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="渠道背景" prop="background">
            <el-input v-model="formData.background" placeholder="请输入渠道背景" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="业务情况" prop="businessSituation">
            <el-input v-model="formData.businessSituation" placeholder="请输入业务情况" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="成长历程" prop="growProcess">
            <el-input v-model="formData.growProcess" placeholder="请输入成长历程" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="优势" prop="advantage">
            <el-input v-model="formData.advantage" placeholder="请输入优势" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="特殊说明" prop="specialDescribe">
            <el-input v-model="formData.specialDescribe" placeholder="请输入特殊说明" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ExpandTargetChannelApi, ExpandTargetChannel } from '@/api/biz/expand/targets/channel'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { defaultProps } from '@/utils/tree'
import * as AreaApi from '@/api/system/area'

/** 拓展目标_渠道 表单 */
defineOptions({ name: 'ExpandTargetChannelForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const areaList = ref([]) // 地区列表

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  location: undefined,
  address: undefined,
  contactName: undefined,
  contactNumber: undefined,
  relationLevel: undefined,
  channelLevel: undefined,
  mainProduct: undefined,
  countMethod: undefined,
  revenueDescribe: undefined,
  transferIntroduceSituation: undefined,
  govSource: undefined,
  personalSource: undefined,
  background: undefined,
  businessSituation: undefined,
  growProcess: undefined,
  advantage: undefined,
  specialDescribe: undefined,
  ownerUserId: undefined
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref

const checkFlag = ref(0)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ExpandTargetChannelApi.getExpandTargetChannel(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (checkFlag.value === 1) {
    message.error('渠道已存在,请检查渠道名称')
    return false
  }
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ExpandTargetChannel
    if (formType.value === 'create') {
      await ExpandTargetChannelApi.createExpandTargetChannel(data)
      message.success(t('common.createSuccess'))
    } else {
      await ExpandTargetChannelApi.updateExpandTargetChannel(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    location: undefined,
    address: undefined,
    contactName: undefined,
    contactNumber: undefined,
    relationLevel: undefined,
    channelLevel: undefined,
    mainProduct: undefined,
    countMethod: undefined,
    revenueDescribe: undefined,
    transferIntroduceSituation: undefined,
    govSource: undefined,
    personalSource: undefined,
    background: undefined,
    businessSituation: undefined,
    growProcess: undefined,
    advantage: undefined,
    specialDescribe: undefined,
    ownerUserId: undefined
  }
  formRef.value?.resetFields()
  checkFlag.value = 0
}

const checkExist = async () => {
  checkFlag.value = await ExpandTargetChannelApi.checkExistByName(formData.value.name)
  if (checkFlag.value === 1) {
    message.error('渠道已存在,请检查渠道名称')
  }
}
</script>
